<template>
  <div class="cart-page">
    <Header :scroll="scroll" />

    <!-- 购物车主体内容 -->
    <div class="cart-container">
      <div class="cart-header">
        <h2>购物车</h2>
        <span class="cart-count">共{{ recordCount }}件商品</span>
      </div>

      <!-- 购物车为空状态 -->
      <div v-if="recordCount === 0" class="empty-cart">
        <div class="empty-cart-icon">
          <img src="@/assets/images/cart-green.png" alt="空购物车" class="empty-icon" />
        </div>
        <p class="empty-text">您的购物车还是空的</p>
        <p class="empty-desc">快去挑选您喜欢的茶叶吧</p>
        <button class="go-shopping-btn" @click="goShopping">去购物</button>
      </div>

      <!-- 购物车有商品状态 -->
      <div v-else class="cart-content">
        <!-- 购物车表头 -->
        <div class="cart-table-header">
          <div class="header-checkbox">
            <el-checkbox v-model="selectAll" @change="handleSelectAll">全选</el-checkbox>
          </div>
          <div class="header-product">商品信息</div>
          <div class="header-price">单价</div>
          <div class="header-quantity">数量</div>
          <div class="header-total">小计</div>
          <div class="header-action">操作</div>
        </div>

        <!-- 购物车商品列表 -->
        <div class="cart-items" v-infinite-scroll="loadMore" :infinite-scroll-disabled="disabled">
          <div v-for="(item, index) in cartItems" :key="item.id" class="cart-item">
            <div class="item-checkbox">
              <el-checkbox v-model="item.selected" @change="updateSelectAll"></el-checkbox>
            </div>
            <div class="item-product">
              <div class="product-image">
                <img :src="proxy.$buildUrl(item.main_image)" :alt="item.spu_name" />
              </div>
              <div class="product-info">
                <h3 class="product-title">{{ item.spu_name }}</h3>
                <p class="product-spec">{{ item.sku_name }}</p>
              </div>
            </div>

            <!-- 桌面端布局 -->
            <div class="item-price desktop-only">
              <span class="price">¥{{ item.actual_price }}</span>
            </div>
            <div class="item-quantity desktop-only">
              <el-input-number v-model="item.quantity" size="large" @change="updateItem(index)" />
            </div>
            <div class="item-total desktop-only">
              <span class="total-price">¥{{ (item.actual_price * item.quantity).toFixed(2) }}</span>
            </div>
            <div class="item-action desktop-only">
              <button class="remove-btn" @click="removeItem(index)">删除</button>
            </div>

            <!-- 移动端布局 -->
            <div class="mobile-item-info mobile-only" v-if="isMobile">
              <div class="mobile-price-quantity">
                <div class="mobile-price">
                  <span class="price-label">单价：</span>
                  <span class="price">¥{{ item.actual_price }}</span>
                </div>
                <div class="mobile-quantity">
                  <span class="quantity-label">数量：</span>
                  <div class="quantity-controls">
                    <button class="quantity-btn decrease" @click="decreaseQuantity(index)" :disabled="item.quantity <= 1">-</button>
                    <input type="number" v-model.number="item.quantity" class="quantity-input" min="1" @change="validateQuantity(index)" />
                    <button class="quantity-btn increase" @click="increaseQuantity(index)">+</button>
                  </div>
                </div>
              </div>
              <div class="mobile-total-action">
                <div class="mobile-total">
                  <span class="total-label">小计：</span>
                  <span class="total-price">¥{{ (item.actual_price * item.quantity).toFixed(2) }}</span>
                </div>
                <button class="remove-btn" @click="removeItem(index)">删除</button>
              </div>
            </div>
          </div>
        </div>

        <!-- 购物车底部结算区域 -->
        <div class="cart-footer" v-if="!isMobile">
          <div class="footer-left">
            <el-checkbox v-model="selectAll" @change="handleSelectAll">全选</el-checkbox>
            <button class="clear-btn" @click="clearSelected">清空选中商品</button>
          </div>
          <div class="footer-right">
            <div class="total-info">
              <span class="selected-count">已选择{{ selectedCount }}件商品</span>
              <div class="total-amount">
                <span class="total-label">合计：</span>
                <span class="total-price">¥{{ totalAmount.toFixed(2) }}</span>
              </div>
            </div>
            <button class="checkout-btn" @click="checkout" :disabled="selectedCount === 0">结算({{ selectedCount }})</button>
          </div>
        </div>
      </div>
    </div>

    <div class="mobile-footer" v-if="isMobile">
      <div class="flex justify-start items-center">
        <span>合计: </span>
        <span class="total">{{ totalAmount.toFixed(2) }}元</span>
      </div>
      <div class="submit-btn" @click="toPay">去结算</div>
    </div>

    <BottomNavbar v-if="isMobile" />
    <!-- 页脚 -->
    <Footer v-if="!isMobile" />
  </div>
</template>

<script setup>
  import { getCurrentInstance, ref, computed, onMounted } from 'vue'
  import { useRouter, useRoute } from 'vue-router'
  import Header from '@/components/Header.vue'
  import Footer from '@/components/Footer.vue'
  import BottomNavbar from '@/components/BottomNavbar.vue'
  import apiOrder from '@/api/modules/order'

  const router = useRouter()
  const route = useRoute()
  const scroll = ref(false)
  const { proxy } = getCurrentInstance()

  // 监听滚动
  window.addEventListener('scroll', () => {
    scroll.value = window.scrollY > 0
  })

  // 购物车商品数据
  const cartItems = ref([])

  // 全选状态
  const selectAll = ref(false)

  // 计算属性
  const selectedCount = computed(() => {
    return cartItems.value.filter((item) => item.selected).length
  })

  const totalAmount = computed(() => {
    return cartItems.value.filter((item) => item.selected).reduce((total, item) => total + item.actual_price * item.quantity, 0)
  })

  // 更新全选状态
  const updateSelectAll = () => {
    selectAll.value = cartItems.value.length > 0 && cartItems.value.every((item) => item.selected)
  }

  // 处理全选
  const handleSelectAll = (checked) => {
    cartItems.value.forEach((item) => {
      item.selected = checked
    })
  }

  // 增加数量
  const increaseQuantity = (index) => {
    cartItems.value[index].quantity++
    updateItem(index)
  }

  // 减少数量
  const decreaseQuantity = (index) => {
    if (cartItems.value[index].quantity > 1) {
      cartItems.value[index].quantity--
      updateItem(index)
    }
  }

  // 验证数量输入
  const validateQuantity = (index) => {
    const item = cartItems.value[index]
    if (item.quantity < 1 || isNaN(item.quantity)) {
      item.quantity = 1
    }
    updateItem(index)
  }

  // 删除商品
  const removeItem = (index) => {
    deleteItem(index)
  }

  // 清空选中商品
  const clearSelected = () => {
    const items = cartItems.value.filter((item) => item.selected)
    if (items && items.length > 0) {
      deleteItems(items)
    }
  }

  // 去购物
  const goShopping = () => {
    router.push('/')
  }

  // 结算
  const checkout = () => {
    if (selectedCount.value === 0) {
      return
    }
    toPay()
  }

  // 跳转支付
  const toPay = () => {
    window.scrollTo(0, 0)
    // 跳转到支付页面
    const items = cartItems.value.filter((item) => item.selected)
    const cartids = items.map((item) => item.id).join(',')
    router.push({
      path: '/order-payment',
      query: {
        cartIds: cartids,
      },
    })
  }

  // 更新商品
  const updateItem = (index) => {
    if (index < 0) {
      return
    }
    const item = cartItems.value[index]
    if (item.quantity > 0) {
      apiOrder.EditShoppingCart(item).then(async (res) => {})
    } else {
      deleteItem(index)
    }
  }

  // 删除商品（一个）
  const deleteItem = (index) => {
    if (index < 0) {
      return
    }
    const item = cartItems.value[index]
    apiOrder.DelShoppingCart({ id: item.id }).then(async (res) => {
      cartItems.value.splice(index, 1)
      updateSelectAll()
    })
  }

  // 删除商品（多个）
  const deleteItems = (items) => {
    if (!(items && items.length > 0)) {
      return
    }
    const ids = items.map((item) => item.id)
    apiOrder.DelShoppingCart({ ids: ids }).then(async (res) => {
      cartItems.value = cartItems.value.filter((item) => !item.selected)
      updateSelectAll()
    })
  }

  // 数据分页查询
  const recordCount = ref(0)
  const page = ref(1)
  const limit = ref(6)

  // 是否正在加载
  const loading = ref(false)
  // 是否还有更多数据
  const hasMore = ref(true)
  // 计算属性 - 是否禁用无限滚动
  const disabled = computed(() => loading.value || !hasMore.value)
  // 计算属性 - 是否没有更多数据
  const noMore = computed(() => !hasMore.value && cartItems.value.length > 0)

  // 分页加载数据
  const fetchData = async (currentPage) => {
    if (loading.value) {
      return
    }
    loading.value = true
    console.log('分页加载数据', currentPage)
    apiOrder
      .GetShoppingCartList({ page: currentPage, limit: limit.value })
      .then(async (res) => {
        loading.value = false
        recordCount.value = res.count
        page.value = currentPage
        hasMore.value = currentPage * limit.value < recordCount.value
        res.data.forEach((item) => {
          item.selected = true // 默认选择
        })
        if (page.value === 1) {
          cartItems.value = res.data
        } else {
          cartItems.value = [...cartItems.value, ...res.data]
        }
        updateSelectAll() // 更新全选状态
      })
      .catch((err) => {
        loading.value = false
      })
  }

  // 加载更多数据
  const loadMore = () => {
    if (!disabled.value) {
      fetchData(page.value + 1)
    }
  }

  // 初始化
  onMounted(() => {
    checkMobile()
    fetchData(1)
  })

  const deviceInfo = ref({
    type: '',
    os: '',
    browser: '',
    screenWidth: 0,
  })
  const getDeviceInfo = () => {
    const userAgent = navigator.userAgent.toLowerCase()
    const screenWidth = window.innerWidth

    // 检测操作系统
    let os = 'Unknown'
    if (userAgent.includes('android')) os = 'Android'
    else if (userAgent.includes('iphone') || userAgent.includes('ipad')) os = 'iOS'
    else if (userAgent.includes('windows')) os = 'Windows'
    else if (userAgent.includes('mac')) os = 'macOS'
    else if (userAgent.includes('linux')) os = 'Linux'

    // 检测浏览器
    let browser = 'Unknown'
    if (userAgent.includes('chrome')) browser = 'Chrome'
    else if (userAgent.includes('firefox')) browser = 'Firefox'
    else if (userAgent.includes('safari')) browser = 'Safari'
    else if (userAgent.includes('edge')) browser = 'Edge'

    // 检测设备类型
    let type = 'Desktop'
    if (userAgent.includes('mobile') || screenWidth <= 768) type = 'Mobile'
    else if (userAgent.includes('tablet') || (screenWidth > 768 && screenWidth <= 1024)) type = 'Tablet'

    deviceInfo.value = { type, os, browser, screenWidth }

    return { type, os, browser, screenWidth }
  }

  // 检测是否为移动设备
  const isMobile = ref(false)
  const checkMobile = () => {
    const { type, screenWidth } = getDeviceInfo()
    const userAgent = navigator.userAgent.toLowerCase()

    // 更精确的移动设备检测
    const mobileKeywords = ['mobile', 'android', 'iphone', 'ipod', 'blackberry', 'windows phone']
    const tabletKeywords = ['ipad', 'tablet']

    const isMobileDevice = mobileKeywords.some((keyword) => userAgent.includes(keyword))
    const isTabletDevice = tabletKeywords.some((keyword) => userAgent.includes(keyword))
    const isSmallScreen = screenWidth <= 768
    const isMediumScreen = screenWidth > 768 && screenWidth <= 1024

    // 移动设备或小屏幕显示移动端界面
    // 平板设备根据屏幕宽度决定
    isMobile.value = isMobileDevice || isSmallScreen || (isTabletDevice && isMediumScreen)
  }
</script>

<style scoped>
  .cart-page {
    width: 1200px;
    margin: auto;
    min-height: 100vh;
    background-color: #f5f5f5;
  }

  /* 购物车容器 */
  .cart-container {
    max-width: 1400px;
    margin: 0 auto;
    padding: 50px 40px;
    background-color: white;
    min-height: calc(100vh - 200px);
  }

  /* 购物车头部 */
  .cart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 30px;
    border-bottom: 2px solid #52a58a;
    margin-bottom: 50px;
  }

  .cart-header h2 {
    font-size: 24px;
    color: #333;
    margin: 0;
  }

  .cart-count {
    font-size: 14px;
    color: #666;
  }

  /* 空购物车状态 */
  .empty-cart {
    text-align: center;
    padding: 120px 40px;
  }

  .empty-cart-icon {
    margin-bottom: 40px;
  }

  .empty-icon {
    width: 150px;
    height: 150px;
    opacity: 0.3;
  }

  .empty-text {
    font-size: 20px;
    color: #333;
    margin-bottom: 15px;
  }

  .empty-desc {
    font-size: 16px;
    color: #999;
    margin-bottom: 50px;
  }

  .go-shopping-btn {
    background-color: #52a58a;
    color: white;
    border: none;
    padding: 15px 40px;
    border-radius: 30px;
    font-size: 18px;
    cursor: pointer;
    transition: background-color 0.3s ease;
  }

  .go-shopping-btn:hover {
    background-color: #459a7e;
  }

  /* 购物车表头 */
  .cart-table-header {
    display: grid;
    grid-template-columns: 80px 1fr 150px 180px 150px 100px;
    gap: 30px;
    align-items: center;
    padding: 10px 0;
    background-color: #f8f9fa;
    border-radius: 12px;
    margin-bottom: 30px;
    font-weight: bold;
    color: #333;
  }

  .header-checkbox,
  .header-product,
  .header-price,
  .header-quantity,
  .header-total,
  .header-action {
    text-align: center;
    font-size: 14px;
  }

  .header-product {
    padding-left: 30px;
  }

  .cart-content {
    margin-bottom: 100px;
  }

  /* 购物车商品项 */
  .cart-item {
    display: grid;
    grid-template-columns: 80px 1fr 150px 180px 150px 100px;
    gap: 30px;
    align-items: center;
    padding: 30px 0;
    border-bottom: 1px solid #eee;
  }

  .item-checkbox {
    text-align: center;
  }

  /* 商品信息 */
  .item-product {
    display: flex;
    align-items: center;
    gap: 20px;
    padding-left: 30px;
  }

  .product-image {
    width: 100px;
    height: 100px;
    border-radius: 12px;
    overflow: hidden;
    flex-shrink: 0;
  }

  .product-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .product-info {
    flex: 1;
  }

  .product-title {
    font-size: 18px;
    color: #333;
    margin: 0 0 12px 0;
    line-height: 1.5;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }

  .product-spec {
    font-size: 14px;
    color: #999;
    margin: 0;
  }

  /* 价格 */
  .item-price {
    text-align: center;
  }

  .price {
    font-size: 18px;
    color: #e53935;
    font-weight: bold;
  }

  /* 数量控制 */
  .item-quantity {
    text-align: center;
  }

  .quantity-controls {
    display: flex;
    align-items: center;
    justify-content: space-around;
    border: 1px solid #ddd;
    border-radius: 4px;
    overflow: hidden;
  }

  .quantity-btn {
    width: 40px;
    height: 40px;
    border: none;
    background: #f5f5f5;
    color: #333;
    font-size: 18px;
    cursor: pointer;
    transition: background-color 0.3s ease;
  }

  .quantity-btn:hover:not(:disabled) {
    background: #e0e0e0;
  }

  .quantity-btn:disabled {
    color: #ccc;
    cursor: not-allowed;
  }

  .quantity-input {
    width: 60px;
    height: 40px;
    border: none;
    text-align: center;
    font-size: 16px;
    outline: none;
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  /* 小计 */
  .item-total {
    text-align: center;
  }

  .total-price {
    font-size: 18px;
    color: #e53935;
    font-weight: bold;
  }

  /* 操作 */
  .item-action {
    text-align: center;
  }

  .remove-btn {
    background: none;
    border: none;
    color: #999;
    font-size: 14px;
    cursor: pointer;
    transition: color 0.3s ease;
  }

  .remove-btn:hover {
    color: #e53935;
  }

  /* 桌面端和移动端显示控制 */
  .mobile-only {
    display: none;
  }

  .desktop-only {
    display: block;
  }

  /* 移动端特有样式 */
  .mobile-item-info {
    display: flex;
    flex-direction: column;
    gap: 15px;
    margin-top: 15px;
  }

  .mobile-price-quantity {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .mobile-price,
  .mobile-quantity {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .mobile-total-action {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .mobile-total {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .price-label,
  .quantity-label,
  .total-label {
    font-size: 14px;
    color: #666;
  }

  /* 购物车底部 */
  .cart-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 40px 30px;
    border-top: 2px solid #eee;
    margin-top: 40px;
    background-color: #fafafa;
    border-radius: 12px;
  }

  .footer-left {
    display: flex;
    align-items: center;
    gap: 30px;
  }

  .clear-btn {
    background: none;
    border: 1px solid #ddd;
    color: #666;
    padding: 12px 24px;
    border-radius: 8px;
    font-size: 16px;
    cursor: pointer;
    transition: all 0.3s ease;
  }

  .clear-btn:hover {
    border-color: #52a58a;
    color: #52a58a;
  }

  .footer-right {
    display: flex;
    align-items: center;
    gap: 40px;
  }

  .total-info {
    text-align: right;
  }

  .selected-count {
    display: block;
    font-size: 16px;
    color: #666;
    margin-bottom: 8px;
  }

  .total-amount {
    display: flex;
    align-items: center;
    gap: 15px;
  }

  .total-label {
    font-size: 18px;
    color: #333;
  }

  .total-amount .total-price {
    font-size: 28px;
    color: #e53935;
    font-weight: bold;
  }

  .checkout-btn {
    background-color: #52a58a;
    color: white;
    border: none;
    padding: 18px 50px;
    border-radius: 30px;
    font-size: 18px;
    font-weight: bold;
    cursor: pointer;
    transition: background-color 0.3s ease;
  }

  .checkout-btn:hover:not(:disabled) {
    background-color: #459a7e;
  }

  .checkout-btn:disabled {
    background-color: #ccc;
    cursor: not-allowed;
  }

  /* 移动端响应式样式 */
  @media (max-width: 768px) {
    .cart-page {
      width: 100%;
    }

    .cart-container {
      padding: 30px 20px;
    }

    .cart-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 15px;
      padding-bottom: 25px;
      margin-bottom: 40px;
    }

    .cart-header h2 {
      font-size: 22px;
    }

    /* 移动端显示控制 */
    .mobile-only {
      display: block;
    }

    .desktop-only {
      display: none;
    }

    /* 移动端隐藏表头 */
    .cart-table-header {
      display: none;
    }

    /* 移动端购物车项目重新布局 */
    .cart-item {
      display: block;
      padding: 25px;
      margin-bottom: 20px;
      background: #f8f9fa;
      border-radius: 12px;
      border-bottom: none;
    }

    .item-checkbox {
      text-align: left;
      margin-bottom: 20px;
    }

    .item-product {
      margin-bottom: 0;
      padding-left: 0;
      gap: 15px;
    }

    .product-image {
      width: 120px;
      height: 120px;
    }

    .product-title {
      font-size: 16px;
    }

    .product-spec {
      font-size: 14px;
    }

    /* 底部结算区域移动端适配 */
    .cart-footer {
      flex-direction: column;
      gap: 25px;
      align-items: stretch;
      padding: 30px 25px;
      margin-top: 30px;
    }

    .footer-left {
      justify-content: space-between;
      gap: 20px;
    }

    .footer-right {
      flex-direction: column;
      gap: 20px;
    }

    .total-info {
      text-align: center;
    }

    .checkout-btn {
      width: 100%;
      padding: 18px;
      font-size: 18px;
    }
  }

  @media (max-width: 480px) {
    .cart-page {
      width: 100%;
    }

    .cart-container {
      padding: 25px 15px;
      width: 100vw;
      max-width: 100vw;
      margin: 0;
    }

    .cart-header {
      padding-bottom: 20px;
      margin-bottom: 30px;
    }

    .cart-header h2 {
      font-size: 20px;
    }

    .empty-cart {
      padding: 80px 20px;
    }

    .empty-icon {
      width: 120px;
      height: 120px;
    }

    .empty-text {
      font-size: 18px;
    }

    .cart-item {
      padding: 20px;
      margin-bottom: 15px;
    }

    .item-checkbox {
      margin-bottom: 15px;
    }

    .product-image {
      width: 100px;
      height: 100px;
    }

    .product-title {
      font-size: 15px;
    }

    .quantity-controls {
      max-width: 140px;
    }

    .quantity-btn {
      width: 35px;
      height: 35px;
      font-size: 16px;
    }

    .quantity-input {
      width: 50px;
      height: 35px;
      font-size: 15px;
    }

    .cart-footer {
      padding: 25px 20px;
      gap: 20px;
    }

    .total-amount .total-price {
      font-size: 24px;
    }

    .checkout-btn {
      padding: 16px;
      font-size: 17px;
    }
  }

  .mobile-footer {
    position: fixed;
    left: 0;
    bottom: 60px;
    width: 100%;
    display: flex;
    justify-content: space-between;
    padding: 20px 10px;
    background-color: white;
    border-top: 1px solid #f0f0f0;

    span {
      font-size: 12px;
    }

    .total {
      color: #af0000;
      font-weight: bold;
      font-size: 14px;
    }

    .submit-btn {
      background-color: #52a58a;
      color: white;
      border: none;
      padding: 10px 30px;
      border-radius: 30px;
      font-size: 12px;
    }
  }
</style>
